<template>
  <q-table
    :data="tableData" :columns="columns"
    row-key="name" class="myTable scroll stick-last-col inherit"
    style="margin-bottom: 20px;max-height: 400px"
    :pagination.sync="pagination" hide-bottom>
    <template v-slot:body-cell-restTimeStr="props">
      <q-td style="width: 190px">
        <yz-input v-model="props.row.restTimeStr"
                  v-if="props.row.edit"
                  v-pureNum
                  class="margin-t-10 margin-b-10"
                  :maxlength="10"
        />
        <div style="width: 180px" v-else>{{ props.row.restTimeStr}}</div>
      </q-td>
    </template>
    <template v-slot:body-cell-processStartTimeStr="props">
      <q-td style="width: 190px">
        <date-picker
          v-model="props.row.processStartTimeStr"
          value-type="format"
          type="datetime"
          :editable="false"
          ref="startTime"
          :showSecond="false"
          v-if="props.row.edit"
          :disabled-date="notAfter"
          :disabled-time="notAfter"
          style="width: 180px;"
          format="YYYY-MM-DD HH:mm"
          placeholder="请选择开工时间"/>
        <div style="width: 180px" v-else>{{ props.row.processStartTimeStr || '--'}}</div>
      </q-td>
    </template>
    <template v-slot:body-cell-processEndTimeStr="props">
      <q-td style="width: 190px">
        <date-picker
          v-model="props.row.processEndTimeStr"
          value-type="format"
          type="datetime"
          :editable="false"
          ref="startTime"
          :showSecond="false"
          v-if="props.row.edit"
          :disabled-date="notAfter"
          :disabled-time="notAfter"
          style="width: 180px;"
          format="YYYY-MM-DD HH:mm"
          placeholder="请选择完工时间"/>
        <div style="width: 180px" v-else>{{ props.row.processEndTimeStr || '--'}}</div>
      </q-td>
    </template>
    <template v-slot:body-cell-processTime="props">
      <q-td>
        {{props.row.processTime}}
      </q-td>
    </template>
    <template v-slot:body-cell-operations="props">
      <q-td style="width: 50px">
        <div class="btn-group" style="text-align: center">
          <div v-if="props.row.edit">
            <q-btn
              style="font-size: 18px"
              flat round dense
              @click="changeTime(props.row)"
              color="primary"
              class="iconfont icontubiao-102"
            >
              <q-tooltip>保存</q-tooltip>
            </q-btn>
            <q-btn
              style="font-size: 18px"
              flat round dense
              @click="props.row.edit = false; cancle(props.row); disEdit = false"
              color="primary"
              class="iconfont icontubiao-89"
            >
              <q-tooltip>取消</q-tooltip>
            </q-btn>
          </div>
          <div v-if="!props.row.edit">
            <table-btn btn-type="edit"
                       :disable="disEdit || props.row.isByCorrectCount || props.row.isAutomatic"
                       @click="props.row.edit=!props.row.edit; disEdit = true;"/>
          </div>
        </div>
      </q-td>
    </template>
  </q-table>
</template>

<script>
import { getOrderCheckinLogs, changeTime } from 'src/boot/job/process-order'
import _ from 'lodash'
import moment from 'moment'
import { MomentJsUtils } from '../../../../assets/js/util'

export default {
  name: 'correction-time',
  data () {
    return {
      now: new Date(),
      // 报工明细表格数据列
      columns: [
        { name: 'id', label: '编号', align: 'left', field: 'id' },
        { name: 'creator', label: '报工人', align: 'left', field: 'creator' },
        { name: 'shiftName', label: '班制', align: 'left', field: 'shiftName' },
        { name: 'time', label: '报工时间', align: 'left', field: 'time' },
        { name: 'checkinCount', label: '报工数量', align: 'left', field: 'checkinCount' },
        { name: 'isAutomaticStr', label: '报工类型', align: 'left', field: 'isAutomaticStr' },
        { name: 'processStartTimeStr', label: '开工时间', align: 'left', field: 'processStartTimeStr' },
        { name: 'processEndTimeStr', label: '完工时间', align: 'left', field: 'processEndTimeStr' },
        { name: 'restTimeStr', label: '休息时长（分钟）', align: 'left', field: 'restTimeStr' },
        { name: 'processTime', label: '加工时间', align: 'left', field: 'processTime' },
        { name: 'operations', label: '操作', field: 'operations', align: 'center' }
      ],
      tableData: [],
      pagination: {
        rowsPerPage: 0
      },
      disEdit: false, // 判断是否点击了编辑以控制按钮启用禁用
      id: null
    }
  },
  methods: {
    getList (id) {
      this.now = new Date()
      this.id = id
      this.$emit('showLoading')
      getOrderCheckinLogs(id).then(res => {
        res.forEach((item, i) => {
          item.edit = false
          item.index = i
          item.restTime = _.floor(item.restTime / 60)
          item.isAutomaticStr = item.isAutomatic ? '数据采集' : '手动录入'
          item.checkinCount = this.$utils.label(item.checkinCount, 0)
          item.creator = this.$utils.label(item.creator)
          item.shiftName = this.$utils.label(item.shiftName)
          item.time = this.$utils.label(item.time)
          item.time = _.isNil(item.time) || _.isEmpty(item.time) ? '-' : moment(item.time).format('YYYY-MM-DD HH:mm')
          item.processStartTime = _.isNil(item.processStartTime) || _.isEmpty(item.processStartTime) ? null : moment(item.processStartTime).format('YYYY-MM-DD HH:mm')
          item.processEndTime = _.isNil(item.processEndTime) || _.isEmpty(item.processEndTime) ? null : moment(item.processEndTime).format('YYYY-MM-DD HH:mm')
          item.processStartTimeStr = item.processStartTime
          item.processEndTimeStr = item.processEndTime
          item.restTimeStr = item.restTime || 0
          const duration = moment.duration(item.processTime, 'seconds')
          item.processTime = MomentJsUtils.humanizeDurationPrecisely(duration, 's')
        })
        this.tableData = res
      }).finally(() => {
        this.$emit('hideLoading')
      })
    },
    // 取消编辑
    cancle (row) {
      row.processStartTimeStr = row.processStartTime
      row.processEndTimeStr = row.processEndTime
      row.restTimeStr = row.restTime
      this.$set(this.tableData, row.index, row)
    },
    notAfter (date, isTime = false) {
      return date > this.now
    },
    getWorkTime (data) {
      const isNil = _.isNil(data.processStartTimeStr) || _.isNil(data.processEndTimeStr)
      const isOver = !_.isNil(data.processStartTimeStr) && !_.isNil(data.processEndTimeStr) && moment(data.processStartTimeStr).isAfter(data.processEndTimeStr, 'minute')
      if (isNil || isOver) {
        return '--'
      } else {
        const workTime = moment(data.processEndTimeStr).diff(moment(data.processStartTimeStr), 'minutes')
        const hour = parseInt(workTime / 60)
        // 获取小时后取佘的分，获取分钟除以60取佘的分
        const minute = parseInt(workTime % 60)
        let label = ''
        hour && (label += `${hour}时`)
        minute && (label += `${minute}分`)
        return label
      }
    },
    getDiffTime (startTime, endTime) {
      const startTimeNew = moment(startTime)
      const endTimeNew = moment(endTime)
      const diffCount = endTimeNew.diff(startTimeNew, 'seconds')
      return _.floor((diffCount < 0 ? 0 : diffCount) / 60)
    },

    // 编辑时间
    changeTime (data) {
      this.$emit('showLoading')
      const isOver = !_.isNil(data.processStartTimeStr) && !_.isNil(data.processEndTimeStr) && moment(data.processStartTimeStr).isAfter(data.processEndTimeStr, 'minute')
      if (isOver) {
        this.$message.warning('开工时间不能晚于完工时间')
        this.$emit('hideLoading')
      } else {
        const params = {
          workOrderCheckinLogId: data.id,
          restTime: _.floor(data.restTimeStr * 60)
        }
        !_.isNil(data.processStartTimeStr) && (params['processStartTime'] = moment(data.processStartTimeStr).format('YYYY-MM-DDTHH:mm'))
        !_.isNil(data.processEndTimeStr) && (params['processEndTime'] = moment(data.processEndTimeStr).format('YYYY-MM-DDTHH:mm'))
        if (data.restTimeStr > this.getDiffTime(params['processStartTime'], params['processEndTime'])) {
          this.$message.warning('休息时长要在开工和完工时间内')
          this.$emit('hideLoading')
          return
        }
        changeTime(this.id, params).then(res => {
          if (res.code === '1200') {
            this.getList(this.id)
            this.disEdit = false
            // this.getList()
            this.$message.success('操作成功')
          }
        }).finally(() => {
          this.$emit('hideLoading')
        })
      }
    }
  }
}
</script>

<style scoped>
/deep/ {
  .q-field__bottom{
    padding: 0;
    min-height: 0;
  }
  .q-field--with-bottom{
    padding: 0;
  }
}

</style>
